import path from 'path'
import fs from 'fs'
import { copyFile, mkdir, writeFile } from 'fs/promises'
import { src, watch, dest, series, parallel } from "gulp";
import uglify from "gulp-uglify" // 压缩文件

import ts from "gulp-typescript" // typescript 编译插件
import { deleteAsync } from "del" // 清理旧文件


const baseDir = __dirname;
const distDir = path.resolve(baseDir, 'dist');


// 清除旧文件
async function clearOldFiles(): Promise<void> {
  await deleteAsync(["dist/**/*"]);
  return
}

// 编译 ts 文件为 js 文件
function buildTypescript(): NodeJS.ReadWriteStream {
  return src("./src/**/*.ts")
    .pipe(
      ts({
        noImplicitAny: false,
        removeComments: false,
        declaration: true,
        target: "es2017",
        module: "commonjs",
        outDir: './dist',
        lib: ["DOM", "ES2015", "ES2016", "ES2017", "ES2018", "ES2022"],
        // moduleResolution: 'node',
        declarationDir: './dist/types'
      })
    )
    .pipe(dest("./dist"));
}

function uglifyJS(): NodeJS.ReadWriteStream {
  return src("dist/*.js")
    .pipe(dest("./dist/"))
    .pipe(uglify())
    .pipe(dest("./dist/"))
}


function readJson(filepath: string) {
  console.log("filepath =", filepath);

  return JSON.parse(fs.readFileSync(filepath).toString())
}


const copyPackageJson = async () => {
  const jsonObj = readJson(path.join(__dirname, 'package.json'));
  const jsonObjProduct = readJson(path.join(__dirname, 'package.production.json'));
  for (const iterator in jsonObjProduct) {
    jsonObj[iterator] = jsonObjProduct[iterator];
  }
  writeFile(path.join(distDir, 'package.json'), JSON.stringify(jsonObj, null, 2));
}


// 用于转移 package.json、README.md 以及声明文件
export const copyFiles = async () => {
  await mkdir(distDir, { recursive: true });
  Promise.all([
    copyPackageJson(),
    copyFile(
      path.join(__dirname, 'readme.md'),
      path.resolve(distDir, 'readme.md')
    ),
    copyFile(
      path.join(__dirname, 'LICENSE'),
      path.resolve(distDir, 'LICENSE')
    )
  ])
}
// 注册监视任务
function watchChanges() {
  // 开启监听
  watch([
    "./src/**/**",
    "./*.ts",
    "./tsconfig.json",
    "LICENSE",
    "package.json",
    "readme.md"
  ], series([
    clearOldFiles, // 启动时先删除旧文件
    buildTypescript, // 编译 ts 为 js
    copyFiles,
  ])
  )
}

// 注册默认任务
const build = series([
  clearOldFiles, // 启动时先删除旧文件
  buildTypescript, // 编译 ts 为 js
  copyFiles,
  watchChanges, // 监视改变
]);

export default build;
